import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Car } from 'src/module/admin/car/entities/car.entity';
import { Cart } from 'src/module/admin/cart/entities/cart.entity';
import { Order } from 'src/module/admin/order/entities/order.entity';
import { Service } from 'src/module/admin/service/entities/service.entity';
import { User } from 'src/module/admin/user/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class CartService {
  constructor(
    @InjectRepository(Cart)
    private readonly cartRepository: Repository<Cart>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Service)
    private readonly serviceRepository: Repository<Service>,
    @InjectRepository(Car)
    private readonly carRepository: Repository<Car>,
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
  ) {}

  async findAll(userId: number): Promise<Array<Cart> | any> {
    const list = await this.cartRepository.find({
      select: ['id', 'type', 'car', 'user', 'service'],
      relations: ['car', 'user', 'service', 'service.photos'],
      where: { user: { id: userId }, isDelete: false },
      order: { id: 'DESC' },
    });

    const result = list.map((item) => {
      return {
        ...item,
        car: {
          id: item.car.id,
          primaryId: item.car.primary_id,
          license_plate: item.car.license_plate,
          brand: item.car.brand,
          status: item.car.status,
        },
        user: {
          id: item.user.id,
          primaryId: item.user.primary_id,
          name: item.user.name,
        },
        service: {
          id: item.service.id,
          primaryId: item.service.primary_id,
          category: item.service.category,
          service_point: item.service.service_point,
          money: item.service.money,
          photo: item.service.photos[0] || {},
        },
      };
    });

    return {
      list: result,
    };
  }

  // 添加一个
  async addCart(userId, params) {
    console.log(userId, params);
    const user = await this.userRepository.findOne({ where: { id: userId } });
    const service = await this.serviceRepository.findOne({
      where: { id: params?.serviceId },
    });
    const car = await this.carRepository.findOne({
      where: { id: params?.carId },
    });

    const cart = new Cart();
    cart.user = user;
    cart.service = service;
    cart.car = car;
    return this.cartRepository.save(cart);
  }

  async addCartOrder(userId, params) {
    const user = await this.userRepository.findOne({
      where: { id: userId, isDelete: false },
    });

    // 判断余额是否够
    if (user.account - params.sum < 0) {
      return {
        code: 901,
        success: false,
        message: '余额不足',
      };
    }

    await this.userRepository.update(
      { id: userId },
      { account: user.account - params.sum },
    );

    const updatedUser = await this.userRepository.findOne({
      where: { id: userId, isDelete: false },
    });

    try {
      const services = params.service;
      for (let i = 0; i < services.length; i++) {
        const order = new Order();
        const car = await this.carRepository.findOne({
          where: { id: services[i].carId, isDelete: false },
        });
        const service = await this.serviceRepository.findOne({
          where: { id: services[i].serviceId, isDelete: false },
        });

        order.user = updatedUser;
        order.car = car;
        order.service = service;

        updatedUser.service = [service];
        car.service = [service];

        await this.userRepository.save(updatedUser);
        await this.carRepository.save(car);
        await this.orderRepository.save(order);
        // 加入成功后删除该购物车内容
        const curCart = await this.cartRepository.findOne({
          where: { id: services[i].cartId },
        });
        await this.cartRepository.remove(curCart);
      }
    } catch (e) {
      // 发生失败
      return {
        code: '901',
        message: '购买失败',
      };
    }

    return {
      code: '200',
      msg: 'success',
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} cart`;
  }

  // update(id: number, updateCartDto: UpdateCartDto) {
  //   return `This action updates a #${id} cart`;
  // }

  remove(id: number) {
    return `This action removes a #${id} cart`;
  }
}
